package mavenWebProject;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * Servlet implementation class SignInServlet
 */
@WebServlet("/SignInServlet")
public class SignInServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SignInServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//1.加载mybatis的核心配置文件，获取sqlsessionfactory
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		
		//2.获取sqlsession对象，用它来执行sql
		SqlSession sqlsession=sqlSessionFactory.openSession();
		
		//3.获取mapper接口的代理对象
		userMapper mapper=sqlsession.getMapper(userMapper.class);
		
		//4.执行方法
		request.setCharacterEncoding("UTF-8");			response.setCharacterEncoding("UTF-8");
		String username=request.getParameter("inputUsername");
		String password=request.getParameter("inputPassword1");
		String[] hobbyList=request.getParameterValues("inputHobbies");
		String hobbies="";
		String location=request.getParameter("inputLocation");
		String gender=request.getParameter("inputGender");
		for(String s:hobbyList) {
			hobbies+=s+" ";
		}
		String tel=request.getParameter("inputTel");
		String accountIdentity="用户";
		List<user> user=mapper.selectByUsername(username);
		int money=0;
		if(user.isEmpty()) {
			mapper.insertAccount(username, password, hobbies, tel,accountIdentity,location,gender,money);
			request.getRequestDispatcher("loadIn.jsp?message=注册成功，请登录").forward(request, response);
			//5.提交事务
			sqlsession.commit();
		}else {
			request.getRequestDispatcher("messagePage.jsp?message=该用户名太受欢迎啦，换一个吧~").forward(request, response);
		}
		
		//6.释放资源
		sqlsession.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
